package com.winit.openapi.ums.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.winit.erp.spi.bpartner.vo.Bpartner;
import com.winit.openapi.constants.ApiConstant;
import com.winit.ums.spi.commnad.*;
import com.winit.ums.spi.customer.command.CheckCustomerVSAccountIdCommand;
import com.winit.ums.spi.customer.command.CreateCustomerVSAccountIdCommand;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.winit.common.spi.command.GetByKeyCommand;
import com.winit.common.spi.context.CommandContext;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.util.DateUtil;
import com.winit.ums.spi.UmsCustomerService;
import com.winit.ums.spi.UmsUserService;
import com.winit.ums.spi.commnad.customer.ActiveModifyUserNameCommand;
import com.winit.ums.spi.commnad.customer.CustomerActviationCommand;
import com.winit.ums.spi.commnad.customer.ModifyCompanyCommand;
import com.winit.ums.spi.commnad.customer.ModifyMaterialCommand;
import com.winit.ums.spi.commnad.customer.ModifyUserNameCommand;
import com.winit.ums.spi.commnad.customer.QueryCompanylCommand;
import com.winit.ums.spi.commnad.customer.agreement.AgreeCustomerAgreementCommand;
import com.winit.ums.spi.commnad.customer.agreement.DenyCustomerAgreementCommand;
import com.winit.ums.spi.commnad.customer.agreement.IsShowCustomerAgreementCommand;
import com.winit.ums.spi.commnad.customer.agreement.QueryCustomerAgreementsByCustomerIdAndTypeCommand;
import com.winit.ums.spi.commnad.user.IsExistsEmailCommand;
import com.winit.ums.spi.commnad.user.PasswordCommand;
import com.winit.ums.spi.commnad.user.QueryAccountByCompanyIdAndTypeCommand;
import com.winit.ums.spi.common.CustomerConstant;
import com.winit.ums.spi.common.command.GetByCodeCommand;
import com.winit.ums.spi.contract.ContractAgreementManagerService;
import com.winit.ums.spi.contract.FileSendManagerService;
import com.winit.ums.spi.contract.command.QueryByCompanyIdAndTypeCommand;
import com.winit.ums.spi.customer.command.CheckCustomerCodeCommand;
import com.winit.ums.spi.customer.command.QueryCustomerByNameCommand;
import com.winit.ums.spi.customer.vo.CompanyVo;
import com.winit.ums.spi.customer.vo.MerchandiseCategoriesTepVo;
import com.winit.ums.spi.customer.vo.SupplyChainTepVo;
import com.winit.ums.spi.customer.vo.SupplyCountryTepVo;
import com.winit.ums.spi.customer.vo.SupplyPeakmonthTepVo;
import com.winit.ums.spi.customer.vo.SupplySlackmonthTepVo;
import com.winit.ums.spi.vo.CustomerCompanyVo;
import com.winit.ums.spi.vo.CustomerInfoVO;
import com.winit.ums.spi.vo.customer.CompanyMaterials;
import com.winit.ums.spi.vo.customer.Contract;
import com.winit.ums.spi.vo.customer.agreement.CustomerAgreementVO;
import com.winit.ums.spi.vo.user.UserVO;

@Controller
@RequestMapping(value = "/customer")
public class CustomerController extends BaseController {

    @Resource
    private UmsCustomerService umsCustomerService;

    @Resource
    private UmsUserService     umsUserService;
    
    @Resource
    private ContractAgreementManagerService contractAgreementManagerService;
    
    @Resource
    private FileSendManagerService  fileSendManagerService;

    /**
     * 客户注册接口
     * 
     * @param requestMsg
     * @param responseMsg
     * @return String
     */
    @RequestMapping(value = "/register")
    public String register(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        // 客户注册
        CustomerCommand command = JSON.parseObject(requestMsg.getData().toString(), CustomerCommand.class);
        command.setCtx(CommandContext.getContext());
        command.setOperator(command.getEmail());
        String coustomCode = umsCustomerService.register(command);
        Map<String, String> data = new HashMap<String, String>();
        data.put("coustomCode", coustomCode);
        responseMsg.setData(data);
        return SUCCESS;
    }
    
    /**
     * 修改客户名称及客户类型(限个人类型转企业类型)
     * 
     * @param requestMsg
     * @param responseMsg
     * @return String
     */
    @RequestMapping(value = "/modifyCustomerAndCustomerType")
    public String modifyCustomerAndCustomerType(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        CustomerCommand command = JSON.parseObject(requestMsg.getData().toString(), CustomerCommand.class);
        command.setCtx(CommandContext.getContext());
        command.setOperator(command.getCtx().getUsername());
        umsCustomerService.modifyCustomerAndCustomerType(command);
        return SUCCESS;
    }

    /**
     * 客户注册验证接口--激活用户
     * 
     * @param requestMsg
     * @param responseMsg
     * @return Boolean
     */
    @RequestMapping(value = "/activeCustomer")
    public String activeCustomer(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        // 客户注册
        CustomerActviationCommand command = JSON.parseObject(requestMsg.getData().toString(), CustomerActviationCommand.class);
        command.setCtx(CommandContext.getContext());
        String result = umsCustomerService.activeCustomer(command);
        Map<String, String> data = new HashMap<String, String>();
        data.put("result", result);
        responseMsg.setData(data);
        return SUCCESS;
    }

    /**
     * 校验用户名是否已存在
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/validateLoginName")
    public String validateLoginName(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        IsExistsEmailCommand command = JSON.parseObject(requestMsg.getData().toString(), IsExistsEmailCommand.class);
        boolean isExists = umsUserService.isExistsEmail(command);
        Map<String, String> data = new HashMap<String, String>();
        data.put("result", isExists ? "Y" : "N");
        responseMsg.setData(data);
        return SUCCESS;
    }

    /**
     * 修改company材料
     * 
     * @param requestMsg
     * @param responseMsg
     * @return Boolean
     */
    @RequestMapping(value = "/modifyMaterial")
    public String modifyMaterial(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        // 客户注册
        ModifyMaterialCommand command = JSON.parseObject(requestMsg.getData().toString(), ModifyMaterialCommand.class);
        command.setCtx(CommandContext.getContext());
        boolean flag = umsCustomerService.modifyMaterial(command);
        Map<String, Boolean> data = new HashMap<String, Boolean>();
        data.put("result", flag);
        responseMsg.setData(data);
        return SUCCESS;
    }

    /**
     * 根据companyId 查询客户基本信息
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/queryCustomerInfo")
    public String queryCustomerInfo(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {

        CommandContext ctx = CommandContext.getContext();
        String userName = ctx.getUsername();
        CustomerQueryCommand userCommand = new CustomerQueryCommand();
        userCommand.setEmail(userName);
        CustomerInfoVO userVo = umsCustomerService.queryUser(userCommand);
        if (null == userVo || null == userVo.getCompanyId()) {
            throw new ApiException(ErrorCode.USER_NOT_FOUND, userName);
        }
        //判断判断当前登陆账号是否为子账号,是子账号则返回主登录账号
        boolean isChildAccount = false;
        String mainAccount = userName;
        if(CustomerConstant.UmsUserType.CHILD.getVal().equals(userVo.getType())){
        	isChildAccount = true;
        	QueryAccountByCompanyIdAndTypeCommand com = new QueryAccountByCompanyIdAndTypeCommand();
        	com.setCompanyId(userVo.getCompanyId());
        	com.setType(CustomerConstant.UmsUserType.MAIN.getVal());
        	UserVO mainUserVO = umsUserService.queryAccountByCompanyIdAndType(com);
        	mainAccount = mainUserVO.getUsername();
        }
        
        GetByKeyCommand<Long> command = new GetByKeyCommand<Long>();
        command.setSearchKey(userVo.getCompanyId());
        command.setCtx(ctx);
        CustomerInfoVO customerInfoVO = umsCustomerService.queryMixCompanyById(command);
        customerInfoVO.setCompanyId(command.getSearchKey());
        
        QueryByCompanyIdAndTypeCommand companyIdAndTypeCommand = new QueryByCompanyIdAndTypeCommand();
        companyIdAndTypeCommand.setCompanyId(userVo.getCompanyId());
        companyIdAndTypeCommand.setType(CustomerConstant.ServiceType.OWHS.getVal());
        contractAgreementManagerService.queryByCompanyIdAndType(companyIdAndTypeCommand);
        
        
        GetAgencyFlagCommand agencyFlagCommand = new GetAgencyFlagCommand();
        agencyFlagCommand.setCompanyId(command.getSearchKey());
        boolean agencyFlag = fileSendManagerService.getAgencyFlag(agencyFlagCommand);    
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        if (customerInfoVO != null) {
            Map<String, Object> map = this.bulidCustomerInfoVO(customerInfoVO,userVo);          
            map.put("agencyFlag",agencyFlag);            
            map.put("companyId", userVo.getCompanyId());
            if(null != userVo.getCreated()){
            	map.put("registerDate",sf.format(userVo.getCreated()));
            }
			if(null != customerInfoVO.getCreated()){
            	map.put("customerRegisterDate",customerInfoVO.getCreated());
            }
            map.put("isChildAccount", isChildAccount);
            map.put("realName", userVo.getUsername());
            map.put("mainAccount", mainAccount);
            map.put("userId", userVo.getId());
            map.put("AD_User_ID", userVo.getAdUserId());
            map.put("C_BPartner_ID", userVo.getcBpartnerId());

            responseMsg.setData(map);
        }
        return SUCCESS;
    }
    
    private Map<String, Object> bulidCustomerInfoVO(CustomerInfoVO customerInfoVO,CustomerInfoVO userVo) {

        Map<String, Object> map = new HashMap<String, Object>();
        // 客户基本信息      
        map.put("companyId", customerInfoVO.getCompanyId());
        map.put("name", customerInfoVO.getName());
        map.put("code", customerInfoVO.getCode());
        map.put("type", customerInfoVO.getType());
        map.put("customerType", customerInfoVO.getCustomerType());
        map.put("contact", customerInfoVO.getContact());
        map.put("phone", customerInfoVO.getPhone());
        map.put("tel", customerInfoVO.getTel());
        map.put("emergencyContact", customerInfoVO.getEmergencyContact());
        map.put("emergencyContactPhone", customerInfoVO.getEmergencyContactPhone());
        map.put("contactsTitle", customerInfoVO.getContactsTitle());
        map.put("contactsTitleName", customerInfoVO.getContactsTitleName());
        map.put("qq", customerInfoVO.getQq());
        map.put("contactEmail", customerInfoVO.getContactEmail());
        map.put("regionId", customerInfoVO.getStateCode());
        map.put("districtId", customerInfoVO.getDistrictCode());
        map.put("cityId", customerInfoVO.getCityCode());
        map.put("countryId", customerInfoVO.getCountryCode());
        map.put("productType", customerInfoVO.getProductType());//发货产品类型
        map.put("development", customerInfoVO.getDevelopment());//开发团队
        map.put("marketingBrief", customerInfoVO.getMarketingBrief());//参加活动
        map.put("recommendChannel", customerInfoVO.getRecommendChannel());//推荐渠道
        map.put("recommenderEmail", customerInfoVO.getRecommenderEmail());//推荐邮箱
        map.put("recommendUser", customerInfoVO.getRecommendUser());//推荐账户 
        map.put("ebayBu",  customerInfoVO.getEbayBu());
        map.put("ebayId", customerInfoVO.getEbayId());
        map.put("ebayAm", customerInfoVO.getEbayAm());
        map.put("tradingReason", customerInfoVO.getTradingReason());
        map.put("companySize", customerInfoVO.getCompanySize());
        map.put("supplayFactoryAddress", customerInfoVO.getSupplayFactoryAddress());
        map.put("contactsModifier", customerInfoVO.getContactsModifier());
        map.put("faxNumber", customerInfoVO.getFaxNumber());
        map.put("customerAgreements", customerInfoVO.getCustomerAgreements());
        map.put("haveBrand", customerInfoVO.getHaveBrand());
        map.put("measurementSystem",customerInfoVO.getMeasurementSystem());
                
        map.put("legalName", customerInfoVO.getLegalName());//法人代表
        map.put("idCardNo", customerInfoVO.getIdCardNo());//法人代表身份证号码
        map.put("averageIncome",customerInfoVO.getAverageIncome());//电商平台月均总营业额       
        map.put("senderName",customerInfoVO.getSenderName());//寄件人姓名
        map.put("senderAddress",customerInfoVO.getSenderAddress());//寄件人地址
        map.put("senderPhone",customerInfoVO.getSenderPhone());//寄件人寄件人号码
        map.put("bankValidate",customerInfoVO.getBankCard());//银行卡认证情况
        map.put("isHaveItsystem", customerInfoVO.getIsHaveItsystem());
        map.put("isHaveErp", customerInfoVO.getIsHaveErp());   
        map.put("winitTransport", customerInfoVO.getWinitTransport());
        map.put("returnCode", customerInfoVO.getReturnCode());// 退货编码
        // 拼装地址
        StringBuilder sbBuilder = new StringBuilder();
        // 大坑，请注意：由于在company表中countryCode保存是国家ID(ERP只有ID，没有code)
        if ("153".equals(customerInfoVO.getCountryCode()) || "316".equals(customerInfoVO.getCountryCode())
        	|| "234".equals(customerInfoVO.getCountryCode()) || "205".equals(customerInfoVO.getCountryCode())) {
            sbBuilder.append(customerInfoVO.getCountry()).append(" ");
            sbBuilder.append(customerInfoVO.getState()).append(" ");
            sbBuilder.append(customerInfoVO.getCity()).append(" ");
            if(StringUtils.isNotBlank(customerInfoVO.getDistrict())){
                sbBuilder.append(customerInfoVO.getDistrict()).append(" ");
            }
            sbBuilder.append(customerInfoVO.getAddress());
        } else {
            sbBuilder.append(customerInfoVO.getAddress()).append(" ");
            if(StringUtils.isNotBlank(customerInfoVO.getDistrict())){
                sbBuilder.append(customerInfoVO.getDistrict()).append(" ");
            }
            sbBuilder.append(customerInfoVO.getCity()).append(" ");
            sbBuilder.append(customerInfoVO.getState()).append(" ");
            sbBuilder.append(customerInfoVO.getCountry());
        }
        
        map.put("address", sbBuilder.toString());
        map.put("addressValue", customerInfoVO.getAddress());
        // 服务及合同
        map.put("legalName", customerInfoVO.getLegalName());
        map.put("idCardNo", customerInfoVO.getIdCardNo());
        List<Map<String, Object>> contractListMap =buildContractListMap(customerInfoVO.getContractList());
        map.put("contractListMap", contractListMap);
        // 审核材料
        List<Map<String, Object>> materialsListMap = new ArrayList<Map<String, Object>>();
        Map<String, Object> materialsMap;
        List<CompanyMaterials> materialsList = customerInfoVO.getMaterialsList();
        for (CompanyMaterials companyMaterials : materialsList) {
            materialsMap = new HashMap<String, Object>();
            materialsMap.put("type", companyMaterials.getType());
            materialsMap.put("status", companyMaterials.getStatus());
            materialsMap.put("image1", companyMaterials.getImage1());
            materialsMap.put("image2", companyMaterials.getImage2());
            materialsMap.put("image3", companyMaterials.getImage3());            
            materialsMap.put("deniedReason", companyMaterials.getDeniedReason());
            materialsMap.put("number", companyMaterials.getNumber());
            materialsMap.put("version", companyMaterials.getVersion());
            materialsMap.put("contractCode", companyMaterials.getContractCode());
            materialsMap.put("expressCompany", companyMaterials.getExpressCompany());
            materialsMap.put("expressNumber", companyMaterials.getExpressNumber());
            materialsListMap.add(materialsMap);
            //设置证件号
            if(CustomerConstant.MaterialType.PASSPORT.getVal().equals(companyMaterials.getType())){
                map.put("passportNo", companyMaterials.getNumber());//联系人护照号 
            }else if(CustomerConstant.MaterialType.BUSINESS.getVal().equals(companyMaterials.getType())){
                map.put("businessNo", companyMaterials.getNumber());//商业登记证号码
            }else if(CustomerConstant.MaterialType.LICENSE.getVal().equals(companyMaterials.getType())){
                map.put("LicenseNo", companyMaterials.getNumber());//营业执照注册号
            }         
        }
        
        map.put("materialsListMap", materialsListMap);
        map.put("customerContactVos", customerInfoVO.getCustomerContactVos());
        
        //供应链
        Map<String, Object> chainMap = new HashMap<String, Object>();
        SupplyChainTepVo chainVos = customerInfoVO.getSupplyChain();
        if(chainVos!=null){
            chainMap.put("supplayAgentorprivat", chainVos.getSupplayAgentorprivat());
            chainMap.put("supplayPrivateFactory", chainVos.getSupplayPrivateFactory());
            chainMap.put("supplayHaveVat", chainVos.getSupplayHaveVat());
            chainMap.put("supplyIor", chainVos.getSupplyIor());
            chainMap.put("supplyPrivateWearhouse", chainVos.getSupplyPrivateWearhouse());
            chainMap.put("supplyCrossEbay", chainVos.getSupplyCrossEbay());
            chainMap.put("supplayWearhouserAddress", chainVos.getSupplayWearhouserAddress());
            chainMap.put("udeskCode", userVo.getUdeskCode());
            map.put("SupplyChainTepVo", chainMap);
        }
        
        
        //海外仓国家
        List<Map<String, Object>> countryMaps = new ArrayList<Map<String, Object>>();
        List<SupplyCountryTepVo> countryList = customerInfoVO.getSupplyCountryTepList();
        if(countryList!=null&&countryList.size()>0){
            for (SupplyCountryTepVo country : countryList) {
                Map<String, Object> countryMap = new HashMap<String, Object>();
                countryMap.put("name", country.getName());
                countryMap.put("code", country.getCode());
                countryMaps.add(countryMap);
            }
        }
        
        map.put("supplyCountryTepList", countryMaps);
        
        //旺季月份
        List<Map<String, Object>> peakMaps = new ArrayList<Map<String, Object>>();
        List<SupplyPeakmonthTepVo> peakList = customerInfoVO.getSupplyPeakmonthTepList();
        if(peakList!=null&&peakList.size()>0){
            for (SupplyPeakmonthTepVo peak : peakList) {
                Map<String, Object> peakMap = new HashMap<String, Object>();
                peakMap.put("name", peak.getName());
                peakMap.put("code", peak.getCode());
                peakMaps.add(peakMap);
            } 
        }
        
        map.put("supplyPeakmonthTepList", peakMaps);
        
        //淡季月份
        List<Map<String, Object>> slackMaps = new ArrayList<Map<String, Object>>();
        List<SupplySlackmonthTepVo> slackList = customerInfoVO.getSupplySlackmonthTepList();
        if(slackList!=null&&slackList.size()>0){
            for (SupplySlackmonthTepVo slack : slackList) {
                Map<String, Object> slackMap = new HashMap<String, Object>();
                slackMap.put("name", slack.getName());
                slackMap.put("code", slack.getCode());
                slackMaps.add(slackMap);
            }
        }
        
        map.put("supplySlackmonthTepList", slackMaps);
        
        //商品分类
        List<Map<String, Object>> merchandiseMaps = new ArrayList<Map<String, Object>>();
        List<MerchandiseCategoriesTepVo> merchandiseList = customerInfoVO.getMerchandiseCategoriesTepList();
        if(merchandiseList != null && merchandiseList.size() > 0){
        	for (MerchandiseCategoriesTepVo merchandise : merchandiseList) {
        		Map<String, Object> merchandiseMap = new HashMap<String, Object>();
        		merchandiseMap.put("name", merchandise.getName());
        		merchandiseMap.put("code", merchandise.getCode());
        		merchandiseMaps.add(merchandiseMap);
			}
        }
        
        map.put("merchandiseCategoriesTepList", merchandiseMaps);
        
        return map;
    }
    
    public List<Map<String, Object>> buildContractListMap(List<Contract> list){
    	 List<Map<String, Object>> contractListMap = new ArrayList<Map<String, Object>>();
         Map<String, Object> contractMap;
         for (Contract contract : list) {
             contractMap = new HashMap<String, Object>();
             contractMap.put("serviceType", contract.getServiceType());
             contractMap.put("contractName", contract.getContractName());
             contractMap.put("signTime", contract.getSignTime());
             contractMap.put("contractValidityPeriod",
                 DateUtil.parse2String(contract.getStartDate(), "yyyy-MM-dd") + " to "
                         + DateUtil.parse2String(contract.getEndDate(), "yyyy-MM-dd"));
             contractMap.put("contractPath", contract.getContractPath());
             contractMap.put("status", contract.getStatus());
             contractMap.put("contractNo", contract.getContractNo());
             contractListMap.add(contractMap);
             /*if(StringUtils.endsWith(contract.getServiceType(), "ISP")){
            	 isSignedIsp=true;
             }else if(StringUtils.endsWith(contract.getServiceType(), "OWHS")){
            	 isSignedOwhs=true;
             }else{
            	 isSignedCbt=true;
             }*/
         }
         
         /*if(!isSignedIsp){
        	 contractMap = new HashMap<String, Object>();
        	 contractMap.put("serviceType", "ISP");
        	 contractMap.put("status", "INIT");
        	 contractListMap.add(contractMap);
         }
         
         if(!isSignedOwhs){
        	 contractMap = new HashMap<String, Object>();
        	 contractMap.put("serviceType", "OWHS");
        	 contractMap.put("status", "INIT");
        	 contractListMap.add(contractMap);
         }
         if(!isSignedCbt){
        	 contractMap = new HashMap<String, Object>();
        	 contractMap.put("serviceType", "CBTR");
        	 contractMap.put("status", "INIT");
        	 contractListMap.add(contractMap);
         }*/

         return contractListMap;
    }
    

    /**
     * 查询公司信息接口
     * 
     * @param requestMsg
     * @param responseMsg
     * @return String
     */
    @RequestMapping(value = "/queryCompany")
    public String queryCompany(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        // 客户注册
        QueryCompanylCommand command = new QueryCompanylCommand();
        command.setCtx(CommandContext.getContext());
        command.setEmail(command.getCtx().getUsername());
        CustomerInfoVO vo = umsCustomerService.queryCompanyByUserName(command);
        Map<String, CustomerInfoVO> data = new HashMap<String, CustomerInfoVO>();
        data.put("comapny", vo);
        responseMsg.setData(data);
        return SUCCESS;
    }

    /**
     * 修改公司信息接口
     * 
     * @param requestMsg
     * @param responseMsg
     * @return String
     */
    @RequestMapping(value = "/modifyBankCard")
    public String modifyBankCard(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        // 客户注册
        ModifyCompanyCommand command = JSON.parseObject(requestMsg.getData().toString(), ModifyCompanyCommand.class);;
        command.setCtx(CommandContext.getContext());       
        umsCustomerService.modifyBankCard(command);
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("flag",true);
        responseMsg.setData(data);
        return SUCCESS;
    }
    /**
     * 授信额度申请
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/customerCreditApply")
    public String customerCreditApply(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {

        CommandContext ctx = CommandContext.getContext();
        String userName = ctx.getUsername();
        GetByKeyCommand<String> userCommand = new GetByKeyCommand<String>();
        userCommand.setSearchKey(userName);
        UserVO userVo = umsUserService.queryByUsername(userCommand);
        if (null == userVo || null == userVo.getCompanyId()) {
            throw new ApiException(ErrorCode.USER_NOT_FOUND, userName);
        }

        GetByKeyCommand<Long> command = new GetByKeyCommand<Long>();
        command.setSearchKey(userVo.getCompanyId());
        CustomerInfoVO customerInfoVO = umsCustomerService.queryMixCompanyById(command);

        if (customerInfoVO != null && null != customerInfoVO.getMaterialsList()
            && customerInfoVO.getMaterialsList().size() > 0) {
            Boolean flag = checkMaterials(customerInfoVO);
            Map<String, Object> resultMap = new HashMap<String, Object>();
            resultMap.put("result", flag);
            responseMsg.setData(resultMap);
        }

        return SUCCESS;
    }
    @RequestMapping(value = "/modifyPassword")
    public String modifyPassword(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        PasswordCommand command = JSON.parseObject(requestMsg.getData().toString(), PasswordCommand.class);
        command.setCtx(CommandContext.getContext());
        umsUserService.modifyPassword(command);
        return SUCCESS;
    }
    
    @RequestMapping(value = "/existCustomerByCode")
    public String existCustomerByCode(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
        JSONObject json = JSONObject.parseObject(requestMsg.getData().toString());
        GetByCodeCommand command = new GetByCodeCommand();
        if (json.containsKey("code")) {
            command.setCode(json.getString("code").trim());
        } else {
            throw new ApiException(ErrorCode.FIELD_NOT_NULL, "CODE");
        }
        CustomerCompanyVo vo = umsCustomerService.queryCompanyByCode(command);
        if (vo == null) {
            responseMsg.setData("");
        } else {
            responseMsg.setData(vo.getEmail());
        }
        return SUCCESS;
    }
    /**
     * 修改用户名
     * 
     * @param requestMsg
     * @param responseMsg
     */
    @RequestMapping(value = "/modifyUserName")
    public String modifyUserName(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        // 客户注册
        ModifyUserNameCommand command = JSON.parseObject(requestMsg.getData().toString(), ModifyUserNameCommand.class);
        command.setCtx(CommandContext.getContext());
        umsCustomerService.modifyUserName(command);
        return SUCCESS;
    }
    
    /**
     * 修改用户名--激活用户
     * 
     * @param requestMsg
     * @param responseMsg
     * @return Boolean
     */
    @RequestMapping(value = "/activeModifyUserName")
    public String activeModifyUserName(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        // 客户注册
        ActiveModifyUserNameCommand command = JSON.parseObject(requestMsg.getData().toString(), ActiveModifyUserNameCommand.class);
        command.setCtx(CommandContext.getContext());
        umsCustomerService.activeModifyUserName(command);
        return SUCCESS;
    }

    /**
     * 是否允许跨仓发货
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/modifyIsAllowAcrossDelivery")
    public String modifyIsAllowAcrossDelivery(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {

        QueryCompanylCommand userCommand = new QueryCompanylCommand();
        userCommand.setEmail(CommandContext.getContext().getUsername());
        CustomerInfoVO customer = umsCustomerService.queryCompanyByUserName(userCommand);
        if(customer == null) {
            throw new ApiException(ErrorCode.SYSTEM_ERROR);
        }

        IfAllowCrossDeliveryCommand command = JSON.parseObject(requestMsg.getData().toString(), IfAllowCrossDeliveryCommand.class);
        command.setCustomerCode(customer.getCode());
        umsCustomerService.modifyIfAllowCrossDelivery(command);
        return SUCCESS;
    }
    
    /**
     * list转map
     * 
     * @param list
     * @return
     */
    private Map<String, CompanyMaterials> materialsMap(List<CompanyMaterials> list) {
        Map<String, CompanyMaterials> map = new HashMap<String, CompanyMaterials>();
        for (CompanyMaterials materials : list) {
            map.put(materials.getType(), materials);
        }
        return map;
    }
    
    private boolean checkMaterials(CustomerInfoVO customerInfoVO){
    	 Map<String, CompanyMaterials> map = this.materialsMap(customerInfoVO.getMaterialsList());
    	
    	if("ENTERPRISE".equals(customerInfoVO.getType())){
    		// 中国企业
        	if ("CN".equals(customerInfoVO.getCustomerType())) {
        		//营业执照、营业执照号、税务登记证、组织机构代码证
        		if(map.get("LICENSE") == null || map.get("LICENSE_NO") == null){
        			return false;
        		}
        		//营业执照
        		if(Strings.isNullOrEmpty(map.get("LICENSE").getImage1()) && Strings.isNullOrEmpty(map.get("LICENSE").getImage2())&& Strings.isNullOrEmpty(map.get("LICENSE").getImage3())){
        			return false;
        		}
        		//营业执照号
        		if(Strings.isNullOrEmpty(map.get("LICENSE_NO").getNumber())){
        			return false;
        		}
            }else {
            	//商业登记证、商业登记证号、公司注册证书
            	if(map.get("BUSINESS") == null || map.get("BUSINESS_NO") == null){
            		return false;
            	}            	
            	//商业登记证
            	if(Strings.isNullOrEmpty(map.get("BUSINESS").getImage1()) && Strings.isNullOrEmpty(map.get("BUSINESS").getImage2())&& Strings.isNullOrEmpty(map.get("BUSINESS").getImage3())){
        			return false;
        		}
            	//商业登记证号
        		if(Strings.isNullOrEmpty(map.get("BUSINESS_NO").getNumber())){
        			return false;
        		}        	
            }
        }else {
	        	if("CN".equals(customerInfoVO.getCustomerType())){//个人
	        	//身份证证件,身份证号
	        	if(map.get("ID") == null || map.get("ID_NO") == null){
	        		return false;
	        	}
	        	
	        	//身份证证件
	    		if(Strings.isNullOrEmpty(map.get("ID").getImage1()) && Strings.isNullOrEmpty(map.get("ID").getImage2())&&Strings.isNullOrEmpty(map.get("ID").getImage3())){
	    			return false;
	    		}
	    		//身份证号
	    		if(Strings.isNullOrEmpty(map.get("ID_NO").getNumber())){
	    			return false;
	    		}
	        }
        }
    	return true;
    }
    
    
    @RequestMapping(value = "/agreeCustomerAgreement")
    public String agreeCustomerAgreement(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
    	AgreeCustomerAgreementCommand command = JSON.parseObject(requestMsg.getData().toString(), AgreeCustomerAgreementCommand.class);
    	umsCustomerService.agreeCustomerAgreement(command);
    	return SUCCESS;
    }
    @RequestMapping(value = "/denyCustomerAgreement")
    public String refuseAgreement(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
    	DenyCustomerAgreementCommand command = JSON.parseObject(requestMsg.getData().toString(), DenyCustomerAgreementCommand.class);
    	umsCustomerService.denyCustomerAgreement(command);
    	return SUCCESS;
    }
    @RequestMapping(value = "/getCustomerAgreement")
    public String queryCustomerAgreement(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
    	QueryCustomerAgreementsByCustomerIdAndTypeCommand command = JSON.parseObject(requestMsg.getData().toString(), QueryCustomerAgreementsByCustomerIdAndTypeCommand.class);
    	CustomerAgreementVO agreement = umsCustomerService.queryCustomerAgreementsByCustomerIdAndType(command);
    	responseMsg.setData(agreement);
    	return SUCCESS;
    }
    @RequestMapping(value = "/isAgreeCustomerAgreement")
    public String isAgreeCustomerAgreement(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
    	IsShowCustomerAgreementCommand command = JSON.parseObject(requestMsg.getData().toString(), IsShowCustomerAgreementCommand.class);
    	Boolean isAgree = umsCustomerService.isShowCustomerAgreement(command);
    	responseMsg.setData(isAgree?"Y":"N");
    	return SUCCESS;
    }
    
    @RequestMapping(value = "/modifyCompanyName")
    public String  modifyCompanyName(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
        ModifyCustomerNameCommand command = JSON.parseObject(requestMsg.getData().toString(), ModifyCustomerNameCommand.class);
        command.setCtx(CommandContext.getContext());
        umsCustomerService.modifyCustomerName(command);
        return SUCCESS;
    }
    
    /**
     * 德国DHL出库单同步地址验证
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/modifyDeliveryDhlAddress")
    public String modifyDeliveryDhlAddress(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
    	DeliveryDhlAddressCommand command = JSON.parseObject(requestMsg.getData().toString(), DeliveryDhlAddressCommand.class);
        command.setCtx(CommandContext.getContext());
        umsCustomerService.modifyDeliveryDhlAddress(command);
        return SUCCESS;
    }
    
    /**
     * 查询德国DHL出库单同步地址验证
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/queryCheckDeliveryDhlAddress")
    public String queryCheckDeliveryDhlAddress(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
    	DeliveryDhlAddressCommand command = JSON.parseObject(requestMsg.getData().toString(), DeliveryDhlAddressCommand.class);
        command.setCtx(CommandContext.getContext());
        String isCheckDhlAddress = umsCustomerService.queryCheckDeliveryDhlAddress(command);
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("isCheckDhlAddress", isCheckDhlAddress);
        responseMsg.setData(resultMap);
        return SUCCESS;
    }
    
    /**
     * 根据客户名称，模糊查询客户，返回客户名称 和 对应的客户编码
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/fuzzyQueryCustomerByName")
    public String fuzzyQueryCustomerByName(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
    	QueryCustomerByNameCommand command = JSON.parseObject(requestMsg.getData().toString(), QueryCustomerByNameCommand.class);
        command.setCtx(CommandContext.getContext());
        List<CompanyVo> list = umsCustomerService.fuzzyQueryCustomerByName(command);
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("customerList", list);
        responseMsg.setData(resultMap);
        return SUCCESS;
    }
    
    /**
     * 验证传入客户编码是否存在，将不存在的客户编码返回
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/checkCustomerCode")
    public String checkCustomerCode(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
    	CheckCustomerCodeCommand command = JSON.parseObject(requestMsg.getData().toString(), CheckCustomerCodeCommand.class);
        command.setCtx(CommandContext.getContext());
        List<String> list = new ArrayList<String>();
        if(command.getCustomerCode() != null){
        	for (int i = 0; i < command.getCustomerCode().size(); i++) {
        		if(StringUtils.isNotBlank(command.getCustomerCode().get(i))){
        			GetByCodeCommand getByCodeCommand = new GetByCodeCommand();
        			getByCodeCommand.setCode(command.getCustomerCode().get(i));
        			CustomerCompanyVo customerCompanyVo = umsCustomerService.queryCompanyByCode(getByCodeCommand);
        			if(customerCompanyVo == null){
        				list.add(command.getCustomerCode().get(i));
        			}
        		}
        		
    		}
        }
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("notCustomerCode", list);
        responseMsg.setData(resultMap);
        return SUCCESS;
    }

    /**
     * 验证传入客户是否存在虚拟账号
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/checkCustomerVSAccountID")
    public String checkCustomerVSAccountID(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
        CheckCustomerVSAccountIdCommand command = new CheckCustomerVSAccountIdCommand();
        if(StringUtils.isNotBlank(requestMsg.getData().toString())){
             command = JSON.parseObject(requestMsg.getData().toString(), CheckCustomerVSAccountIdCommand.class);
        }
        command.setCtx(CommandContext.getContext());
        if(StringUtils.isBlank(command.getCompanyCode())){
            Bpartner bpartner = command.getCtx().get(ApiConstant.API_BPARTNER);
            command.setCompanyCode(bpartner.getValue());
        }
        String isVSAccountID=umsCustomerService.checkCustomerVSAccountID(command);
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("isVSAccountID", isVSAccountID);
        responseMsg.setData(resultMap);
        return SUCCESS;
    }

    /**
     * 为客户创建虚拟账号
     * @param requestMsg
     * @param responseMsg
     * @return
     */

    @RequestMapping(value = "/createCustomerVSAccountID")
    public String createCustomerVSAccountID(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
        CreateCustomerVSAccountIdCommand command = new CreateCustomerVSAccountIdCommand();
        if(StringUtils.isNotBlank(requestMsg.getData().toString())){
            command = JSON.parseObject(requestMsg.getData().toString(), CreateCustomerVSAccountIdCommand.class);
        }
        command.setCtx(CommandContext.getContext());
        if(StringUtils.isBlank(command.getCompanyCode())){
            Bpartner bpartner = command.getCtx().get(ApiConstant.API_BPARTNER);
            command.setCompanyCode(bpartner.getValue());
        }
        String result=umsCustomerService.createCustomerVSAccountID(command);
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("CustomerVSAccountID", result);
        responseMsg.setData(resultMap);
        return SUCCESS;
    }
}
